package cn.aiweiyi.qingjing.coupon.template.service.impl;

import cn.aiweiyi.qingjing.coupon.comm.exception.CouponException;
import cn.aiweiyi.qingjing.coupon.template.dao.CouponTemplateDao;
import cn.aiweiyi.qingjing.coupon.template.entity.CouponTemplate;
import cn.aiweiyi.qingjing.coupon.template.service.AsyncService;
import cn.aiweiyi.qingjing.coupon.template.service.BuildTemplateService;
import cn.aiweiyi.qingjing.coupon.comm.vo.TemplateRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author 青衿
 * @Date 2020/11/17 10:59
 * 根据用户请求创建优惠券模板的主业务流程,异步生成是由此调用的
 **/
@Slf4j
@Service
public class BuildTemplateServiceImpl implements BuildTemplateService {
    @Autowired
    CouponTemplateDao couponTemplateDao;

    @Autowired
    AsyncService asyncService;

    @Override
    public CouponTemplate bulidTemplate(TemplateRequest req) throws CouponException {
        if (!req.validate()) {//在执行内部校验
            throw new CouponException("模板的参数无效,创建失败!");
        }
        if (null != couponTemplateDao.findByName(req.getName())) {
            throw new CouponException("模板名称已存在,创建失败!");
        }
        CouponTemplate template = request2Template(req);
        template = couponTemplateDao.save(template);
        asyncService.asyncConstructCouponByTemplate(template);
        return template;
    }

    private CouponTemplate request2Template(TemplateRequest req) {
        return new CouponTemplate(req.getName(),
                req.getLogo(),
                req.getDesc(),
                req.getCategory(),
                req.getProductLine(),
                req.getCount(),
                req.getUserId(),
                req.getTarget(),
                req.getRule());
    }
}
